/*
 * Copyright (c) 2008, 2010
 *      Toni Spets <toni.spets@iki.fi>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef _SOCKETS_H_

#include <stdint.h>

#ifdef __WIN32
#include <winsock.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define lprintf printf
#endif

#define NET_PORT 8054

extern int sock;

typedef struct _ra_client
{
    uint32_t ip;
    uint16_t port;
    uint8_t magic;
} __attribute__ ((packed)) ra_client_t;

typedef struct _ra_buffer {
    ra_client_t         from;
    uint8_t             direct;
    uint8_t             data[993]; /* highest packet length seen: 540 bytes */
} __attribute__ ((packed)) ra_buffer_t;

typedef struct _ra_packet
{
    uint16_t            nul;
    uint16_t            len;
    uint8_t             _magic[18];
    ra_buffer_t         buffer;
} __attribute__ ((packed)) ra_packet_t;

#define net_socket() socket(AF_INET, SOCK_DGRAM, 0)
#define net_send(a, b, c, d) sendto(a, b, c, 0, (struct sockaddr *)d, sizeof(struct sockaddr))
#define net_bind(a, b) bind(a, (struct sockaddr *)b, sizeof(struct sockaddr));

void net_init();
void net_free();
uint8_t net_broadcast(uint16_t sock);
uint8_t net_reuse(uint16_t sock);
uint8_t net_address(struct sockaddr_in *addr, char *host, uint16_t port);
uint8_t net_address_ex(struct sockaddr_in *addr, uint32_t ip, uint16_t port);
int32_t net_recv(uint16_t sock, char *buf, uint32_t len, struct sockaddr_in *who);

#define _SOCKETS_H_
#endif
